const express = require('express')
// 生成ID
const { v4: uuidv4 } = require('uuid')
// 引入jwt token工具
const JwtUtil = require('../../utils/jwt');
const multer = require('multer');
let fs = require('fs')
const config = require('../../sql/baseinfo')
const HostUrl = `${config.PROTOCOL}://${config.HOST}:${config.PORT}`
const router = express.Router()
// 一级路由： /user
// 二级路由： /register
// http://127.0.0.1:3005/user/register
// 导入已封装的数据函数
const db = require('../../sql/db.js')

// 增加数据(注册)
router.post('/register', function (req, res) {
    let id = uuidv4() || Math.random().toString().slice(2);
    let userName = req.body.userName; // 用户名
    let passWord = req.body.passWord; // 密码
    let email = req.body.email; //  邮箱
    let phone = req.body.phone; //  手机号
    let time = req.body.time || '2022-09-29 00:00:00'; //  用户创建的时间
    // 查询用户表
    let user_check_sql = 'select * from user where email="' + email + '" or phone = "' + phone + '"';
    db.query(user_check_sql, (err, rows) => {
        if (err) {
            res.send({
                code: -1,
                msg: '查询失败'
            })
        } else {
            // 解构赋值(数据库)
            if (rows && rows.length != 0) {
                let [user] = rows;
                if (user.email == email || user.phone == phone) {
                    res.send({
                        code: 201,
                        msg: '用户已存在'
                    })
                } else {
                    res.send({
                        code: 501,
                        msg: '后端异常'
                    })
                }
            }
            else {
                // 添加用户
                let user_insert_sql = 'insert into User(userName,passWord,id,email,phone,time,count) values(' + '"' + userName + '"' + ',' + '"' + passWord + '"' + ',' + '"' + id + '"' + ',' + '"' + email + '"' + ',' + '"' + phone + '"' + ',' + '"' + time + '"' + ',0)';
                db.query(user_insert_sql, (err) => {
                    if (err) {
                        res.send({
                            code: -1,
                            msg: '注册失败',
                            err: err,
                        })
                    } else {
                        res.send({
                            code: 200,
                            msg: '注册成功',
                            userName: userName
                        });
                    }
                })
            }

        }
    })
})

// 查询数据(登录)
router.post('/login', function (req, res) {
    // let userName = req.body.userName;
    let passWord = req.body.passWord;
    let email = req.body.email;
    let phone = req.body.phone;
    console.log(email, phone);
    // 查询用户表
    let user_check_sql = 'select * from user where passWord="' + passWord + '" and email="' + email + '" or phone = "' + phone + '"';
    db.query(user_check_sql, (err, rows) => {
        if (err) {
            res.send({
                code: -1,
                msg: '登录失败'
            })
        } else {
            if (rows && rows.length == 0) {
                res.send({
                    code: 404,
                    msg: '账号或密码错误'
                });
            } else {

                let [{ id, userName, email, phone, avatar, shop_cart, userAddress,allorder }] = rows;
                // 将用户id传入并生成token
                let jwt = new JwtUtil(id);
                // 获取token
                let token = jwt.generateToken();
                let user_update_sql = 'update user set token = "' + token + '" where id="' + id + '"';
                db.query(user_update_sql, (err, rows) => {
                    if (err) {
                        res.send({
                            code: -1,
                            msg: '修改失败',
                            err: err
                        })

                    } else {

                        res.send({
                            code: 200,
                            msg: '登录成功',
                            token,
                            userName,
                            email,
                            phone,
                            avatar,
                            shop_cart,
                            userAddress,
                            allorder
                        })
                    }
                })
                // 将 token 返回给客户端


            }
        }
    })
})

//获取用户信息
router.get('/userinfor', function (req, res) {
    // 前端接收参数
    let token = req.query.token;
    // console.log(token,'123');
    // 查询用户表
    let user_check_sql = 'select * from user where token="' + token + '"';
    db.query(user_check_sql, (err, rows) => {
        if (err) {
            res.send({
                code: -1,
                msg: '查询失败'
            })
        } else {
            // console.log(rows);
            let [{ userName, email, phone, avatar }] = rows;
            res.send({
                code: 200,
                msg: '查询成功',
                userName,
                email,
                phone,
                avatar
            })
        }
    })
})
// 修改密码数据
router.get('/update', function (req, res) {
    let phone = req.query.phone;
    let passWord = req.query.passWord;
    let email = req.query.email;
    let token = req.query.token;
    let userName = req.query.userName;
    // 请求需要进行token校验 
    let jwt = new JwtUtil(token);
    // 返回一个对象 
    let result = jwt.verifyToken();
    // 验通过执行下一步，否则就返回登陆信息不正确
    if (result == 'err') {
        res.send({
            code: -1,
            msg: '登录已过期,请重新登录'
        });
    } else {
        if (result.data) {
            let user_check_sql = 'select * from user where token = "' + token + '"'
            db.query(user_check_sql, (err, rows) => {
                if (err) {
                    res.send({
                        code: -1,
                        msg: '查询失败'
                    })
                } else {
                    if (rows && rows.length != 0) {
                        let user_update_sql = 'update user set passWord = "' + passWord + '",userName="' + userName + '" where token="' + token + '"';
                        db.query(user_update_sql, function (err) {
                            if (err) {
                                res.send({ code: -1, msg: "修改密码失败" });
                            } else {
                                res.send({ code: 200, msg: "修改密码成功" });
                            }
                        });
                    }

                }
            })
        }
    }


})
// 添加收货地址数据
router.get('/address', function (req, res) {
    let token = req.query.token;
    // let userName = req.query.userName;
    let address = JSON.stringify(req.query.address).replace(/\"/g,"'");
    // let address = req.query.address;
    console.log(address);
    // 请求需要进行token校验 
    let jwt = new JwtUtil(token);
    // 返回一个对象 
    let result = jwt.verifyToken();
    // 验通过执行下一步，否则就返回登陆信息不正确
    if (result == 'err') {
        res.send({
            code: -1,
            msg: '登录已过期,请重新登录'
        });
    } else {
        if (result.data) {
            let user_check_sql = 'select * from user where token = "' + token + '"'
            db.query(user_check_sql, (err, rows) => {
                if (err) {
                    res.send({
                        code: -1,
                        msg: '查询失败'
                    })
                } else {
                    if (rows && rows.length != 0) {
                        let user_update_sql = 'update user set userAddress = "' +  address  + '" where token =   "' + token + '"';
                        db.query(user_update_sql, function (err, rows) {
                            if (err) {
                                res.send({ code: -1, msg: "添加失败" + err });
                            } else {
                                res.send({ code: 200, msg: "添加成功" + rows });
                            }
                        });
                    }

                }
            })
        }
    }


})
//添加购物车数据
router.get('/shopcart', function (req, res) {
    let token = req.query.token;
    // let userName = req.query.userName;
    let shop = JSON.stringify(req.query.shop).replace(/\"/g,"'");
    // let address = req.query.address;
    console.log(shop);
    // 请求需要进行token校验 
    let jwt = new JwtUtil(token);
    // 返回一个对象 
    let result = jwt.verifyToken();
    // 验通过执行下一步，否则就返回登陆信息不正确
    if (result == 'err') {
        res.send({
            code: -1,
            msg: '登录已过期,请重新登录'
        });
    } else {
        if (result.data) {
            let user_check_sql = 'select * from user where token = "' + token + '"'
            db.query(user_check_sql, (err, rows) => {
                if (err) {
                    res.send({
                        code: -1,
                        msg: '查询失败'
                    })
                } else {
                    if (rows && rows.length != 0) {
                        let user_update_sql = 'update user set shop_cart = "' +  shop  + '" where token =   "' + token + '"';
                        db.query(user_update_sql, function (err, rows) {
                            if (err) {
                                res.send({ code: -1, msg: "添加失败" + err });
                            } else {
                                res.send({ code: 200, msg: "添加成功" + rows });
                            }
                        });
                    }

                }
            })
        }
    }


})
//添加一户订单数据
router.get('/userorder', function (req, res) {
    let token = req.query.token;
    // let userName = req.query.userName;
    let allorder = JSON.stringify(req.query.allorder).replace(/\"/g,"'");
    // let address = req.query.address;
    console.log(allorder);
    // 请求需要进行token校验 
    let jwt = new JwtUtil(token);
    // 返回一个对象 
    let result = jwt.verifyToken();
    // 验通过执行下一步，否则就返回登陆信息不正确
    if (result == 'err') {
        res.send({
            code: -1,
            msg: '登录已过期,请重新登录'
        });
    } else {
        if (result.data) {
            let user_check_sql = 'select * from user where token = "' + token + '"'
            db.query(user_check_sql, (err, rows) => {
                if (err) {
                    res.send({
                        code: -1,
                        msg: '查询失败'
                    })
                } else {
                    if (rows && rows.length != 0) {
                        let user_update_sql = 'update user set allorder = "' +  allorder  + '" where token =   "' + token + '"';
                        db.query(user_update_sql, function (err, rows) {
                            if (err) {
                                res.send({ code: -1, msg: "添加失败" + err });
                            } else {
                                res.send({ code: 200, msg: "添加成功" + rows });
                            }
                        });
                    }

                }
            })
        }
    }


})
// 处理图片
// 通过filename属性定制
let storage = multer.diskStorage({
    // 保存的路径
    destination: function (req, file, callback) {
        callback(null, 'public/upload/')
    },
    filename: function (req, file, callback) {
        // 将保存文件名设置为 字段名 + 时间戳，比如 logo-1478521468943
        let suffix = file.mimetype.split('/')[1]; //获取文件格式
        callback(null, file.fieldname + '-' + Date.now() + '.' + suffix);
    }
});
//生成的图片放入uploads文件夹下
let upload = multer({
    storage: storage
})
// 保存头像到后台
router.post('/modify_avatar', upload.single('avatar'), function (req, res) {
    let file = req.file
    // console.log(req.file);
    // console.log(req.headers);
    if (!file) {
        res.send({
            code: -1,
            msg: '上传失败'
        })
    }
    else {
        res.send({
            code: 200,
            msg: '上传成功',
            file: file
        })
    }

})
//把头像路径保存到数据库
router.get('/avatar_sql', function (req, res) {
    // 请求需要进行token校验 
    let token = req.query.token;
    let jwt = new JwtUtil(token)
    let result = jwt.verifyToken()
    // 接收前端的参数
    if (result == 'err') {
        res.send({
            code: -1,
            msg: '登录已过期,请重新登录'
        })
    } else {
        // 接收前端的文件
        let file = req.query.file
        // 定义存在在服务器的图片的路径（存在数据库的路径）
        let image = `${HostUrl}/static/upload/${file.filename}`
        let id = result.data;
        let user_check_sql = "select * from user where id='" + id + "'";
        db.query(user_check_sql, (err, rows) => {
            if (err) {
                res.send({
                    code: -1,
                    msg: '查询失败'
                })
            } else {
                if (rows && rows.length != 0) {
                    var user_update_sql = "update user set avatar = '" + image + "' where  id = '" + id + "'";
                    db.query(user_update_sql, function (err, rows) {
                        if (err) {
                            res.send({
                                code: -1,
                                msg: "修改失败"
                            });
                        } else {
                            res.send({
                                code: 200,
                                msg: "修改头像成功",
                                avatar: image
                            });
                        }
                    });
                }
            }
        })
    }
})

module.exports = router;
